Visualiser les données est une étape cruciale lorsqu'on analyse les données actuarielles. les actuaires sont d'abord passionnés par les chifre afin d'analyser les différents risques. Souvent les données sont en forme de tableau, il est important de prendre l'habitude de visualiser les données sous forme de graphique afin d'avoir un apperçu rapide. Pensez seulement au doonées abhérantes.
Il y'a plusieurs manières de isualiser les données avec R. Dans ce cours, nous utilisons le package ggplot2, ce dernier est très riche cohérent dans la création de graphique, il est aussi le plus utilisé dans la communauté scioentique, l'aide sur internet est aussi très abondante.
library(ggplot2)
pour faire les démonstarions, travaillerons dans les prochains exemples avec les données mpg qui sont aussi dans le package ggplot2.
head(mpg)
Nous nous aintéréssons alors à la relation entre la taille du moteur displ et hwy, l'efficacité énergétique d'une voiture sur l'autoroute, en miles par gallon(mpg). Une voiture à faible rendement énergétique consomme plus de carburant que une voiture à haut rendement énergétique lorsqu'ils parcourent la même distance.
Chaque fonction geom dans ggplot2 prend un argument de mappage. Ceci définit comment les variables de votre ensemble de données sont mappées aux propriétés visuelles. L'argument de mappage est toujours associé à aes (), et les arguments x et y de aes () spécifient les variables à mapper avec les axes x et y. ggplot2 recherche la variable mappée dans l'argument de données, dans ce cas, mpg
ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy))
Dans le graphique précédent, on ne peut distinguer les catégories de voitures, on aimerait distinguer ces catégories dans le graphique. Pour ce faire, nous devons modifier "l'esthétique" (aesthetic) du graphique. On peut alors ajouter une troisième variable comme la classe, à un nuage de points bidimensionnel. L'esthétique comprend des choses comme la taille, la forme ou la couleur de vos points.
ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy, color = class))
Si on utilise l'argument alpha, on obitent alors;
ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy, alpha = class))
ou la variable shape
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, shape = class))
on obtient un avertissemnt nous indiquons que l'argument shape contient seulement 6 catégories et que dans nos donnés nous en avons 7:
Une autre méthode, particulièrement utile pour les variables catégorielles, consiste à diviser le graphique en facettes, sous-placettes qui affichent chacune un sous-ensemble des données.
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_wrap(~ class, nrow = 2)
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_grid(drv ~ cyl)
head(mpg)
unique(mpg$drv)
unique(mpg$cyl)
A<-ggplot(data = mpg) +
geom_smooth(mapping = aes(x = displ, y = hwy))
B<-ggplot(data = mpg) +
geom_smooth(mapping = aes(x = displ, y = hwy, linetype = drv))
# install.packages("ggpubr")
library(ggpubr)
ggarrange(A, B,
labels = c("A", "B"),
ncol = 1, nrow = 2)
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point(mapping = aes(color = class)) +
geom_smooth()
regardons les données d'assurance que nous avons;
data<-read.csv("../données/donnes_demo.csv")
head(data)
library(data.table)
ageebreaks <- c(0,20,25,30,35,40,45,50,55,60,65,70,75,80,85,500)
ageelabels <- c("0-19","20-24","25-29","30-34",
"35-39","40-44","45-49","50-54","55-59","60-64","65-69",
"70-74","75-79","80-84","85+")
data<-setDT(data)[ , ageegroups := cut(agee,
breaks = ageebreaks,
right = FALSE,
labels = ageelabels)]
head(data)
ggplot(data, aes(agee)) +
geom_bar()
ggplot(data, aes(agee)) +
geom_histogram(bins = 30, binwidth = 0.5,)
ggplot(data, aes(data$age_permis)) +
geom_histogram(bins = 30, binwidth = 0.5,)
# ?sort
sort(unique(data$age_permis))
qplot(data$agee,
geom="histogram",
binwidth = 0.5,
main = "Histogram for Age",
xlab = "Age",
fill=I("blue"),
col=I("red"),
alpha=I(.2))
ggplot(data=data, aes(data$age_permis)) +
geom_histogram(breaks=seq(15, 50, by = .5),
col="red",
fill="green",
alpha = .2) +
labs(title="Histogram for Age") +
labs(x="Age", y="Count")
ggplot(data=data, aes(data$age_permis)) +
geom_histogram(breaks=seq(15, max(data$age_permis), by = .5),
col="pink",
fill="pink",
alpha = .5) +
labs(x="Age", y="Count") +
theme(axis.title = element_text(color="#559977", size=14, face="bold"))+
ggtitle("L'âge de l'assuré \n à l'obtention du permis")
require("datasets")
head(chickwts)
plot(chickwts$feed)
On va regarder une autre fonction appelée barplot. Toutfois, cette fonction nécessite une préparation des données. Nous allons alors préparer ces données
feeds<-table(chickwts$feed)
feeds
barplot(feeds)
L'avantage d'utiliser barplot c'est qu'il est possible de modifier cette fonction
?barplots
barplot(feeds[order(feeds, decreasing = T)])
lesAges<-table(data$agee)
lesAges
par(oma=c(1,1,1,1)) # set outside margin
par(mar=c(4,5,2,1))
barplot(feeds[order(feeds)],
horiz=T,
las=1, #orientation de l'axe des x
col=c("beige", "bisque1", "bisque2", "bisque3", "bisque4", "bisque4"),
border=NA,
main="La fréquence de différentes alimentation \n des poulets",
xlab="nombre de poulets")
dat <- data.frame(
examen =c("Examen_1","Examen_2"),
moyenne = c(20, 24)
)
ggplot(data=dat, aes(x=examen, y=moyenne)) +
geom_bar(stat="identity")
En couleur, on différencie chacun des examen
ggplot(data=dat, aes(x=examen, y=moyenne, fill=examen)) +
geom_bar(stat="identity")
Ajoutons un ecadré noir:
ggplot(data=dat, aes(x=examen, y=moyenne, fill=examen)) +
geom_bar(col="black",stat="identity")
On voit bien que la légende ne sert pas à grande chose
ggplot(data=dat, aes(x=examen, y=moyenne, fill=examen)) +
geom_bar(stat="identity")+
guides(fill=FALSE)
Travaillons avec les vraies couleurs
ggplot(data=dat, aes(x=examen, y=moyenne, fill=examen)) +
geom_bar(colour="black", fill="#f293ce", width=.8, stat="identity") +
guides(fill=FALSE) +
xlab("Examen") + ylab("Moyenne de la classe") +
ggtitle("Moyenne du premier \net deuxième exmamen")
ggplot(data=dat, aes(x=examen, y=moyenne, fill=examen)) +
geom_bar(colour="black", fill=c("#7A41A6","#3C811E"), width=.8, stat="identity") +
guides(fill=FALSE) +
xlab("Examen") + ylab("Moyenne de la classe") +
ggtitle("Moyenne du premier \net deuxième exmamen")+
theme(plot.title = element_text(hjust = 0.5))
# install.packages("reshape2")
library(reshape2)
head(tips)
ggplot(data=tips, aes(x=day)) +
geom_bar(stat="count")
ggplot(data=dat, aes(x=examen, y=moyenne,group=1))+ #puisque on a un seul groupe de points
geom_line()
# ggplot(data=dat, aes(x=time, y=total_bill)) +
# geom_line(aes(group=1))
ggplot(data=dat, aes(x=examen, y=moyenne))+
geom_line(aes(group=1))
Ajouter des points:
ggplot(data=dat, aes(x=examen, y=moyenne,group=1))+
geom_line() +
geom_point()
ggplot(data=dat, aes(x=examen, y=moyenne,group=1))+
geom_line(colour="red", linetype="dashed", size=1.5) +
geom_point(colour="red", size=4, shape=21, fill="white")
dat2 <- data.frame(
examen =c("Examen_1","Examen_2","Examen_3"),
moyenne = c(20, 24, 26)
)
ggplot(data=dat2, aes(x=examen, y=moyenne,group=1))+
geom_line() +
geom_point() +
expand_limits(y=0) +
xlab("Examen") + ylab("Moyenne") +
ggtitle("Évolution de la moyenne \ndes examens du cours ACT3035") +
theme(plot.title = element_text(hjust = 0.5))
dat3 <- data.frame(
session = factor(c("S1","S1","S2","S2")),
examen = c("Examen_1","Examen_2","Examen_1","Examen_2"),
moyenne = c(20, 24, 21, 22)
)
head(dat3)
ggplot(data=dat3, aes(x=examen, y=moyenne, fill=session)) +
geom_bar(stat="identity")
ggplot(data=dat3, aes(x=examen, y=moyenne, fill=session)) +
geom_bar(stat="identity", position=position_dodge())
ggplot(data=dat3, aes(x=examen, y=moyenne, fill=session)) +
geom_bar(stat="identity", position=position_dodge(), colour="black")
dat4 <- data.frame(
session = factor(c("S1","S1","S1","S2","S2","S2")),
examen = c("Examen_1","Examen_2", "Examen_3","Examen_1","Examen_2", "Examen_3"),
moyenne = c(20, 24, 26, 21, 22, 23)
)
head(dat4)
ggplot(data=dat4, aes(x=examen, y=moyenne, fill=session)) +
geom_bar(stat="identity", position=position_dodge(), colour="black")+
scale_fill_manual(values=c("#f293ce", "#a5bcef")) +
xlab("Examen") + ylab("Moyenne") +
ggtitle("Évolution de la moyenne \ndes examens du cours ACT3035") +
theme(plot.title = element_text(hjust = 0.5))
ggplot(data=dat4, aes(x=examen, y=moyenne, group=session, fill=session)) +
geom_line() +
geom_point()
ggplot(data=dat4, aes(x=examen, y=moyenne, group=session, fill=session, color=session)) +
geom_line() +
geom_point()
ggplot(data=dat4, aes(x=examen, y=moyenne, group=session, fill=session, color=session)) +
geom_errorbar(aes(ymin=len-ci, ymax=len+ci), colour="black", width=.1, position=pd) +
geom_line(position=pd) +
geom_point(position=pd, size=3)
$${\sigma }_{\bar {x}}\ ={\frac {\sigma }{\sqrt {n}}}$$
dat4$se<-c(.33, .27, .5, .25, .7, .5)
dat4
ggplot(dat4, aes(x=examen, y=moyenne, colour=session, group=session,)) +
geom_errorbar(aes(ymin=moyenne-se, ymax=moyenne+se), width=.1) +
geom_line() +
geom_point()
ggplot(dat4, aes(x=examen, y=moyenne, colour=session, group=session,)) +
geom_errorbar(aes(ymin=moyenne-se, ymax=moyenne+se), colour="black", width=.1) +
geom_line() +
geom_point(size=3)
ggplot(dat4, aes(x=examen, y=moyenne, fill=session)) +
geom_bar(position=position_dodge(), stat="identity") +
geom_errorbar(aes(ymin=moyenne-se, ymax=moyenne+se),
width=.2, # Width of the error bars
position=position_dodge(.8),
size=.3 # Thinner lines
)+
ggtitle("Évolution de la moyenne \ndes examens du cours ACT3035") +
theme(plot.title = element_text(hjust = 0.5))
library(Rmisc)
tgc <- summarySE(tg, measurevar="len", groupvars=c("supp","dose"))
tgc
ggplot(tgc, aes(x=dose, y=len, colour=supp)) +
geom_errorbar(aes(ymin=len-se, ymax=len+se), width=.1) +
geom_line() +
geom_point()
pie(feeds) #un ballon de plage
pie(feeds[order(feeds, decreasing = T)],
init.angle=90,
clockwise=T,
col=c("beige", "bisque1", "bisque2", "bisque3", "grey", "bisque4"),
main="La fréquence de différentes alimentation \n des poulets")
With bar charts, each column represents a group defined by a categorical variable; and with histograms, each column represents a group defined by a continuous, quantitative variable.

head(lynx)
hist(lynx)
h<-hist(lynx,
breaks=11,
freq=FALSE,
col="thistle1",
main="Nombre de lynx attrapé depuis 1834 \n au Canada",
xlab="nombre de lynx attrapés")
set.seed(1234)
dat <- data.frame(cond = factor(rep(c("A","B"), each=200)),
rating = c(rnorm(200),rnorm(200, mean=.8)))
head(dat)
tail(dat)
Créons un histogram qui représente les valeurs de la colonne rating
ggplot(dat, aes(x=rating)) + geom_histogram(binwidth=.5)
Dans le graphique plu haut, on ne voit pas bien les séparations;
ggplot(dat, aes(x=rating)) +
geom_histogram(binwidth=.5, colour="black", fill="white")
ggplot(dat, aes(x=rating)) + geom_density()
ggplot(dat, aes(x=rating)) +
geom_histogram(aes(y=..density..), # Histogram with density instead of count on y-axis
binwidth=.5,
colour="black", fill="white") +
geom_density(alpha=.2, fill="#FF6666") # Overlay with transparent density plot
ggplot(dat, aes(x=rating)) +
geom_histogram(binwidth=.5, colour="black", fill="white") +
geom_vline(aes(xintercept=mean(rating, na.rm=T)), # Ignore NA values for mean
color="red", linetype="dashed", size=1)
ggplot(dat, aes(x=rating, fill=cond)) +
geom_histogram(binwidth=.5, alpha=.5, position="identity")
ggplot(dat, aes(x=rating, fill=cond)) +
geom_histogram(binwidth=.5, position="dodge")
ggplot(dat, aes(x=rating, colour=cond)) + geom_density()
ggplot(dat, aes(x=rating, fill=cond)) + geom_density(alpha=.3)
library(plyr)
cdat <- ddply(dat, "cond", summarise, rating.mean=mean(rating))
cdat
ggplot(dat, aes(x=rating, fill=cond)) +
geom_histogram(binwidth=.5, alpha=.5, position="identity") +
geom_vline(data=cdat, aes(xintercept=rating.mean, colour=cond),
linetype="dashed", size=1)
ggplot(dat, aes(x=rating, colour=cond)) +
geom_density() +
geom_vline(data=cdat, aes(xintercept=rating.mean, colour=cond),
linetype="dashed", size=1)
ggplot(dat, aes(x=cond, y=rating)) + geom_boxplot()
ggplot(dat, aes(x=cond, y=rating, fill=cond)) + geom_boxplot()
ggplot(dat, aes(x=cond, y=rating, fill=cond)) + geom_boxplot() +
guides(fill=FALSE)
ggplot(dat, aes(x=cond, y=rating, fill=cond)) + geom_boxplot() +
guides(fill=FALSE) + coord_flip()
df_app <-read.csv("../cours_10/stocks_correlation.csv", header = T)[ ,2:9]
mat_corr<-cor(df_app)
# install.packages("ellipse")
library(ellipse)
mat_corr
library(ggplot2)
# install.packages("ggcorrplot")
library(ggcorrplot)
ggcorrplot(mat_corr)
ggcorrplot(mat_corr, method = "circle")
ggcorrplot(mat_corr, hc.order = TRUE,
lab = TRUE)
ggcorrplot(mat_corr, hc.order = TRUE, type = "lower",
lab = TRUE)
data(mtcars)
corr <- round(cor(mtcars), 1)
head(corr[, 1:6])
p.mat <- cor_pmat(mtcars)
p.mat[, 1:4]
ggcorrplot(corr, hc.order = TRUE,
type = "lower", p.mat = p.mat)
colorfun <- colorRamp(c("#CC0000","white","#3366CC"), space="Lab")
plotcorr(mat_corr, col=rgb(colorfun((mat_corr+1)/2), maxColorValue=255),
mar = c(0.1, 0.1, 0.1, 0.1))
ggsave("mtcars.pdf")
ggsave("mtcars.png")
ggsave("mtcars.pdf", width = 4, height = 4)
ggsave("mtcars.pdf", width = 20, height = 20, units = "cm")
library(ggplot2)
library(dplyr)
insurance <- read.csv("https://raw.githubusercontent.com/nmeraihi/data/master/insurance.csv")
insurance$smoker <- as.factor(insurance$smoker)
head(insurance)
insurance %>%
ggplot(aes(x=smoker, y = charges, fill = smoker, colour = smoker)) +
geom_violin()
insurance %>%
ggplot(aes(x= bmi, y= charges, colour = smoker)) + geom_point() +
geom_smooth(method="lm")
insurance.smoker <- insurance %>% filter(smoker == "yes")
fit <- lm(charges ~ bmi, data = insurance.smoker)
fit
x = 30
charge.amount <- 1473*x + -13187
charge.amount
install.packages("GGally")
library(GGally)
ggpairs(insurance[-7])
insurance$group <- ifelse(insurance$charges > mean(insurance$charges), "high", "low")
ggpairs(insurance, aes(color=group, alpha=0.75), lower=list(continuous="smooth"))+ theme_bw()